package com.leapp.sk.viewdelegate.adapter.im

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import cc.vv.lkbasecomponent.util.LKDateTimeUtil
import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.body.LKIMTxtBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMStatus
import cc.vv.lkimcomponent.view.emoji.ParseEmojiOperate
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.baselibrary.db.dao.AccountDao
import com.example.baselibrary.db.table.AccountTable
import com.example.mvp.delegate.BaseAdapterDelegate
import com.example.mvp.view.GlideCircleTransform
import com.example.mvp.view.LKCircleImageView
import com.leapp.sk.R
import com.leapp.sk.ui.activity.im.MessageStateActivity
import com.leapp.sk.util.IMDialogUtil
import com.leapp.sk.util.SKTimeUtil
import com.example.util.finallist.*
import com.leapp.sk.util.im.BigEmojiconDatas
import java.util.*

/**
 * 单聊适配器视图托管层
 * @author  chaohaipeng  on 2018/7/17.
 */
class SingleChatAdapterDelegale : BaseAdapterDelegate() {

    val text: TextView? = null
    /**
     * 图片加载操作
     */
    var mRequestOptions: RequestOptions = RequestOptions()
    /**
     * 头像加载操作
     */
    var mHeadRequestOptions: RequestOptions = RequestOptions()

    override fun getOptionsMenuId(): Int {
        return 0
    }

    override fun initWidget() {
    }

    override fun onDestroy() {
    }

    override fun initLayoutRes(): Int {
        return R.layout.sk_chat_send_text_message

    }

    /**
     * 设置收到消息View
     */
    fun setRecerveView(context: Context, lkimMessage: LKIMMessage, timeInterval: Int, position: Int) {
        val v_scstm_receive_root = getView<RelativeLayout>(R.id.v_scstm_receive_root)
        val rl_scstm_send_root = getView<RelativeLayout>(R.id.rl_scstm_send_root)
        v_scstm_receive_root.visibility = View.VISIBLE
        rl_scstm_send_root.visibility = View.GONE
        setRecerveData(context, lkimMessage, timeInterval, position)
    }

    /**
     * 设置收到消息数据
     */
    private fun setRecerveData(context: Context, lkimMessage: LKIMMessage, timeInterval: Int, position: Int) {
        val tv_scstm_time = getView<TextView>(R.id.tv_scstm_time)
        val tv_scstm_receive_nick = getView<TextView>(R.id.tv_scstm_receive_nick)
        val lav_scstm_receive_avatar = getView<LKCircleImageView>(R.id.lav_scstm_receive_avatar)
        val tv_scstm_receive_content = getView<TextView>(R.id.tv_scstm_receive_content)
        val rl_scstm_receive_content = getView<RelativeLayout>(R.id.rl_scstm_receive_content)
        tv_scstm_receive_nick.visibility=View.VISIBLE
        tv_scstm_time.text = LKDateTimeUtil.formatDateTime(lkimMessage.msgTime, "")
        isShowTime(tv_scstm_time, timeInterval, lkimMessage.msgTime, position)
        val iv_scstm_receive_image = getView<ImageView>(R.id.iv_scstm_receive_image)
        var lkImBody: LKIMTxtBody? = null
        try {
            lkImBody = lkimMessage.lkIMBody as LKIMTxtBody
        } catch (e: Exception) {
            lkImBody = null
        }
        if (getBigEmohincon(lkImBody?.message) != 0) {
            tv_scstm_receive_content.visibility = View.GONE
            iv_scstm_receive_image.visibility = View.VISIBLE
            val mRequestManager: RequestManager = Glide.with(context)
            mRequestOptions.diskCacheStrategy(DiskCacheStrategy.NONE)
            mRequestOptions.skipMemoryCache(true)
            mRequestOptions.error(R.mipmap.ease_default_expression)
            mRequestOptions.transforms(GlideCircleTransform(context))
            mRequestManager?.load(getBigEmohincon(lkImBody?.message))
                    ?.thumbnail(0.2f)
                    ?.apply(mRequestOptions)
                    ?.into(iv_scstm_receive_image)
        } else {
            tv_scstm_receive_content.visibility = View.VISIBLE
            iv_scstm_receive_image.visibility = View.GONE
            val spannableString = ParseEmojiOperate.getInstance().parseEmoji(lkImBody?.message, 20)//Emoji解析
           // val smiledText = EmojiconUtils.getSmiledText(context, lkImBody?.message)
            tv_scstm_receive_content.text = spannableString
        }
        val headUrl = lkimMessage.getAttribute(IMExtKey.EXTKEY_AVATAR, "")
        val nick = lkimMessage.getAttribute(IMExtKey.EXTKEY_NICK, "")

        val accountTable = AccountDao.getInstance().queryById(lkimMessage.fromAccount)
        if (accountTable==null||!TextUtils.equals( accountTable.avatar,headUrl)||!TextUtils.equals( accountTable.nick,nick)){
            val accountTable = AccountTable()
            accountTable.avatar=headUrl
            accountTable.nick=nick
            accountTable.account=lkimMessage.fromAccount
            tv_scstm_receive_nick.text =nick
            AccountDao.getInstance().createOrUpdate(accountTable)
            setHead(context, headUrl, lav_scstm_receive_avatar)
        }else{
            val avatar = if (null == accountTable) "" else accountTable.avatar
            val nick = if (null == accountTable) LKStringUtil.getString(R.string.app_name) else accountTable.nick
            tv_scstm_receive_nick.text =nick
            setHead(context, avatar, lav_scstm_receive_avatar)
        }

        val activity = context as Activity
        rl_scstm_receive_content.setOnLongClickListener(View.OnLongClickListener {
            IMDialogUtil.getInstance().longClickEvent(activity, lkimMessage)
            true
        })
    }

    /**
     * 设置头像和昵称
     */
    fun setHead(context: Context, headUrl: String?, headImage: LKCircleImageView) {
        val tag = headImage.getTag(R.id.tag_head)
        if (tag == null || !tag?.equals(headUrl)) {
            val mRequestManager = Glide.with(context)
            mHeadRequestOptions?.diskCacheStrategy(DiskCacheStrategy.NONE)
            mHeadRequestOptions?.skipMemoryCache(true)
            mHeadRequestOptions?.error(R.mipmap.icon_defout_head)
            mHeadRequestOptions?.transforms(GlideCircleTransform(context))
            mRequestManager?.load(headUrl)
                    ?.thumbnail(0.2f)
                    ?.apply(mHeadRequestOptions)
                    ?.into(headImage)
            headImage.setTag(R.id.tag_head, headUrl)
        }
    }


    /**
     * 发送数据View
     */
    fun setSendDataView(context: Context, lkimMessage: LKIMMessage, timeInterval: Int, position: Int) {
        val rl_scstm_send_root = getView<RelativeLayout>(R.id.rl_scstm_send_root)
        val v_scstm_receive_root = getView<RelativeLayout>(R.id.v_scstm_receive_root)
        val tv_scstm_send_msgStatus_def_yes = getView<TextView>(R.id.tv_scstm_send_msgStatus_def_yes)
        val pb_scstm_send_im_sending = getView<ProgressBar>(R.id.pb_scstm_send_im_sending)
        val iv_scstm_send_im_fail = getView<ImageView>(R.id.iv_scstm_send_im_fail)
        rl_scstm_send_root.visibility = View.VISIBLE
        v_scstm_receive_root.visibility = View.GONE
        if (lkimMessage.lkimStatus == LKIMStatus.FAIL) {
            tv_scstm_send_msgStatus_def_yes.visibility = View.INVISIBLE
            pb_scstm_send_im_sending.visibility = View.INVISIBLE
            iv_scstm_send_im_fail.visibility = View.VISIBLE
        } else if (lkimMessage.lkimStatus == LKIMStatus.SUCCESS) {
            setReadInfo(context, lkimMessage)
        } else {
            tv_scstm_send_msgStatus_def_yes.visibility = View.INVISIBLE
            iv_scstm_send_im_fail.visibility = View.INVISIBLE
            pb_scstm_send_im_sending.visibility = View.VISIBLE
        }
        setSendData(context, lkimMessage, timeInterval, position)

    }

    /**
     * 设置已读信息
     */
    fun setReadInfo(context: Context, lkimMessage: LKIMMessage) {
        val tv_scstm_send_msgStatus_def_yes = getView<TextView>(R.id.tv_scstm_send_msgStatus_def_yes)
        val pb_scstm_send_im_sending = getView<ProgressBar>(R.id.pb_scstm_send_im_sending)
        val iv_scstm_send_im_fail = getView<ImageView>(R.id.iv_scstm_send_im_fail)
        if (LKIMChatType.GroupChat == lkimMessage.lkimChatType) {
            val groupMemerCount = Integer.valueOf(lkimMessage.getAttribute(IMExtKey.EXTKEY_GROUPMEMERCOUNT, SkKey.BTKEY_String_0))
            val readMembersCount = Integer.valueOf(lkimMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERSCOUNT, SkKey.BTKEY_String_0))
            val unReadMemberCount = groupMemerCount - readMembersCount
            if (unReadMemberCount > 0) {
                tv_scstm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context, R.color.color_4390E1))
                tv_scstm_send_msgStatus_def_yes.text = String.format(Locale.CHINESE, LKStringUtil.getString(R.string.string_im_unread_portion), unReadMemberCount)
            } else {
                tv_scstm_send_msgStatus_def_yes.text = context.resources.getString(R.string.string_im_read)
                tv_scstm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context, R.color.color_C0C0C0))
            }
        } else {
            if (TextUtils.equals(lkimMessage.isAcked, "1")) {
                tv_scstm_send_msgStatus_def_yes.text = context.resources.getString(R.string.string_im_read)
                tv_scstm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context, R.color.color_C0C0C0))
            } else {
                tv_scstm_send_msgStatus_def_yes.text = context.resources.getString(R.string.string_im_unread)
                tv_scstm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context, R.color.color_4390E1))
            }

        }
        tv_scstm_send_msgStatus_def_yes.visibility = View.VISIBLE
        pb_scstm_send_im_sending.visibility = View.INVISIBLE
        iv_scstm_send_im_fail.visibility = View.INVISIBLE
    }


    /**
     * 发送数据View
     */
    private fun setSendData(context: Context, lkimMessage: LKIMMessage, timeInterval: Int, position: Int) {
        val tv_scstm_time = getView<TextView>(R.id.tv_scstm_time)
        val tv_scstm_send_content = getView<TextView>(R.id.tv_scstm_send_content)
        val lav_scstm_send_avatar = getView<LKCircleImageView>(R.id.lav_scstm_send_avatar)
        tv_scstm_time.text = LKDateTimeUtil.formatDateTime(lkimMessage.msgTime, "")
        isShowTime(tv_scstm_time, timeInterval, lkimMessage.msgTime, position)
        val iv_scstm_send_image = getView<ImageView>(R.id.iv_scstm_send_image)
        val lkImBody: LKIMTxtBody = lkimMessage.lkIMBody as LKIMTxtBody
        if (getBigEmohincon(lkImBody.message) != 0) {
            tv_scstm_send_content.visibility = View.GONE
            iv_scstm_send_image.visibility = View.VISIBLE
            val mRequestManager: RequestManager = Glide.with(context)
            mRequestOptions.diskCacheStrategy(DiskCacheStrategy.NONE)
            mRequestOptions.skipMemoryCache(true)
            mRequestOptions.error(R.mipmap.ease_default_expression)
            mRequestOptions.transforms(GlideCircleTransform(context))
            mRequestManager?.load(getBigEmohincon(lkImBody.message))
                    ?.thumbnail(0.2f)
                    ?.apply(mRequestOptions)
                    ?.into(iv_scstm_send_image)
        } else {
            tv_scstm_send_content.visibility = View.VISIBLE
            iv_scstm_send_image.visibility = View.GONE
            try {
                val lkImBody: LKIMTxtBody = lkimMessage.lkIMBody as LKIMTxtBody
                val spannableString = ParseEmojiOperate.getInstance().parseEmoji(lkImBody?.message, 20)//Emoji解析
           //   val smiledText = EmojiconUtils.getSmiledText(context, lkImBody.message)
                tv_scstm_send_content.text = spannableString
            } catch (e: Exception) {
            }

        }
        val headUrl = lkimMessage.getAttribute(IMExtKey.EXTKEY_AVATAR, "")
        val nick= lkimMessage.getAttribute(IMExtKey.EXTKEY_NICK,"")
        val accountTable = AccountDao.getInstance().queryById(lkimMessage.fromAccount)
        if (accountTable==null){
            accountTable?.avatar=headUrl
            accountTable?.nick=nick
            accountTable?.account=lkimMessage.fromAccount
            setHead(context,headUrl,lav_scstm_send_avatar)
        }else{
            val avatar = if (null == accountTable) "" else accountTable.avatar
            setHead(context,avatar,lav_scstm_send_avatar)
        }
        val activity = context as Activity
        initEvent(activity, lkimMessage)
    }


    /**
     * 初始化事件
     */
    fun initEvent(context: Activity, lkimMessage: LKIMMessage) {
        val tv_scstm_send_msgStatus_def_yes = getView<TextView>(R.id.tv_scstm_send_msgStatus_def_yes)
        val rl_scstm_send_content = getView<RelativeLayout>(R.id.rl_scstm_send_content)
        tv_scstm_send_msgStatus_def_yes.setOnClickListener(object : View.OnClickListener {
            override fun onClick(p0: View?) {
                if (lkimMessage.lkimChatType == LKIMChatType.GroupChat) {
                    val unReadMemberIds = lkimMessage.getAttribute(IMExtKey.EXTKEY_UNREADMEMBERIDS, "")
                    val readMemberIds = lkimMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERIDS, "")
                    val intent = Intent(context, MessageStateActivity::class.java)
                    intent.putExtra(READ_MESSAGE_IDS, readMemberIds)
                    intent.putExtra(UNREAD_MESSAGE_IDS, unReadMemberIds)
                    intent.putExtra(MSG_DATA,lkimMessage)
                    intent.putExtra(GROUP_ID, lkimMessage.toAccount)
                    context?.startActivity(intent)
                }

            }
        })
        rl_scstm_send_content.setOnLongClickListener(View.OnLongClickListener {
            IMDialogUtil.getInstance().longClickEvent(context, lkimMessage)
            true
        })

    }


    /**
     * 获取大表情资源
     */
    fun getBigEmohincon(iden: String?): Int {
        var icon = 0

        val data = BigEmojiconDatas.getData()
        val emojiconList = data.emojiconList
        if (emojiconList != null && emojiconList.size > 0) {
            for (i in emojiconList.indices) {
                val get = emojiconList.get(i)
                if (TextUtils.equals(get.identityCode, iden)) {
                    icon = get.bigIcon
                    break
                }
            }
        }

        return icon

    }


    /**
     * 间隔时间处理
     *
     * @param tv_time
     * @param timeInterval
     * @param time
     */
    private fun isShowTime(tv_time: TextView, timeInterval: Int, time: Long, position: Int) {
        if (timeInterval >= 5) {
            val dayOrHours = SKTimeUtil.getDayOrHours(time)
            tv_time.text = dayOrHours
            tv_time.visibility = View.VISIBLE
        } else {
            if (position == 0) {
                val dayOrHours = SKTimeUtil.getDayOrHours(time)
                tv_time.text = dayOrHours
                tv_time.visibility = View.VISIBLE
            } else {
                tv_time.visibility = View.GONE
            }

        }
    }
}